<template>
  <BaseDialog
    :visible="visible"
    :title="isEditMode ? '编辑分组' : '添加分组'"
    width="400px"
    footer-type="default"
    @update:visible="$emit('update:visible', $event)"
    @close="$emit('close')"
    @cancel="$emit('close')"
    @confirm="handleSave"
  >
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item v-if="!isEditMode" label="上级目录" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="menuTreeData"
          :props="treeSelectProps"
          placeholder="请选择上级目录"
          check-strictly
          :render-after-expand="false"
          :default-expanded-keys="[1]"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="分组名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入分组名称" />
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElForm, ElFormItem, ElInput, ElTreeSelect } from 'element-plus'
import { getAllMenu, createMenu, updateMenuName } from '@/api/device'
import { buildTree } from '@/utils/tree'
import type { DeviceMenu } from '@/types'

// Props
interface Props {
  visible: boolean
  isEditMode: boolean
  groupData?: { id: number; name: string; parentId?: number } | null
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'close': []
  'save': [data: { id?: number; name: string; parentId?: number }]
  'refresh': []
  'update:visible': [value: boolean]
}>()

// 表单数据
const formData = reactive({
  id: null as number | null,
  name: '',
  parentId: 1 // 默认选择根目录（id为1）
})

// 菜单树数据
const menuTreeData = ref<DeviceMenu[]>([])

// 树选择器配置
const treeSelectProps = {
  value: 'id',
  label: 'name',
  children: 'children'
}

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入分组名称', trigger: 'blur' }],
  parentId: [{ required: true, message: '请选择上级目录', trigger: 'change' }]
}

// 表单引用
const formRef = ref()

// 加载菜单树数据
const loadMenuTreeData = async () => {
  try {
    const response = await getAllMenu()
    const flatMenuData = response.data || []
    menuTreeData.value = buildTree(flatMenuData)
    console.log('加载的菜单树数据:', menuTreeData.value)
  } catch (error) {
    console.error('加载菜单数据失败:', error)
  }
}

// 监听props变化，更新表单数据
watch(() => props.groupData, (newData) => {
  if (newData) {
    Object.assign(formData, {
      id: newData.id,
      name: newData.name,
      parentId: newData.parentId || 1
    })
  } else {
    // 重置表单
    Object.assign(formData, {
      id: null,
      name: '',
      parentId: 1
    })
  }
}, { immediate: true })

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate()
    
    if (props.isEditMode) {
      // 编辑模式：只更新名称
      if (formData.id) {
        await updateMenuName(formData.id, formData.name)
        emit('save', { id: formData.id, name: formData.name })
      }
    } else {
      // 添加模式：创建新菜单
      const newMenu = await createMenu({
        name: formData.name,
        parentId: formData.parentId
      })
      emit('save', { 
        id: newMenu.data.id, 
        name: formData.name, 
        parentId: formData.parentId 
      })
    }
    
    // 保存成功后发出刷新事件
    emit('refresh')
  } catch (error) {
    console.error('保存失败:', error)
  }
}

// 组件挂载时加载菜单数据
onMounted(() => {
  loadMenuTreeData()
})
</script>

<style scoped>
/* 组件样式可以在这里添加 */
</style>
